# -*- coding: utf-8 -*- 
import requests
import json
import uuid
import os
import struct
import subprocess
import time
import sys,signal
import threading
import logging

import commands
 
import socket
import platform

from threading import Thread
import socketNet
import models
import moniterCP


g_pushRTMPMap = {}

g_subPushPid = -1

g_push = 'push'

def pkillNames(nameList):

	# rip = name
	# me = commands.getoutput("whoami")
	# p = commands.getoutput("ps -u %s -o cmd -o pid |grep %s" % (me,name) )
	msg =''

	for name in nameList:
		msg = msg+'-e '+name+' '

	msgline = "ps -o cmd -o pid |grep "+msg
	print msgline
	p = commands.getoutput(msgline)

	ids = p.split("\n")

	# print u'发起全部停止操作:'+name
	for id in ids:
		kpid =id.split(' ')
		print kpid 
		kpidStr = unicode(''.join(kpid[-1:]))
		if kpidStr.isdecimal():
			print "kill %d" % int(kpidStr)
			os.system("kill %d" % int(kpidStr))

def pkillAll(nameList):

	for name in nameList:
		logging.info('kill ' + name)
		os.system('pkill ' + name)



def cddPushRtmp(res):
	url = res['url']
	cddid = res['cddid']
	sourcesid = res['sourcesid']


	idflag = g_push+"_"+cddid

	logging.info('推流开始:'+str(url))


	if res.has_key('mp4'):
		msgline = 'ffmpeg -re -i ' + str(res['mp4']) + ' -c copy -f flv ' + url
	elif res.has_key('rtsp'):
		#msgline = './push.bin push'+' '+res['rtsp'] +' '+url +' '+idflag
		msgline = 'ffmpeg -f lavfi -i anullsrc -rtsp_transport tcp -i '+res['rtsp']+' -vcodec libx264 -t 2:00:00 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv '+url
	# msgline = './push.bin push'+' '+rtsp +' '+url +' '+idflag
	# msgline = 'ffmpeg -re -i ' + 'localFile.mp4 -c copy -f flv rtmp://server/live/streamName'

	logging.info('推流执行命令:'+str(msgline))

	push_thread = threading.Thread(target=pushRTMPCommendexec, name="pushRTMPThread",args = (msgline,cddid,))
	# getImage_thread.setDaemon(True)
	push_thread.start()


def cddStopRtmp(res):
	cddid = res['cddid']

	if g_pushRTMPMap.has_key(cddid):
		
		try:
			proc = g_pushRTMPMap[cddid]
			proc.terminate()
			proc.wait()
			os.killpg(proc.pid, signal.SIGTERM)
		except Exception as e:
			print e


def pushRTMPCommendexec(func,cddid):
	res = subprocess.Popen(func, stdin=subprocess.PIPE, stdout=subprocess.PIPE,shell = True, preexec_fn = os.setpgrp)
	global g_subPushPid
	g_subPushPid =res.pid
	global g_pushRTMPMap
	g_pushRTMPMap[cddid] = res

	logging.info('推流执行进程 pid:'+str(res.pid))




